package 笔试.睿联技术;

import java.util.TimeZone;

class 时间戳转换字符串 {
    public static void main(String[] args) {
        long timestamp = 1693910400000L; // 示例时间戳

        // 是否与本机时区保持一致
        boolean flag = false;
        if (flag) {
            // 获取系统默认时区的偏移量（毫秒）
            int offset = TimeZone.getDefault().getOffset(timestamp);
            // 将时间戳加上时区偏移
            timestamp += offset;
        }

        // 将时间戳从毫秒转换为秒
        long totalSeconds = timestamp / 1000;

        // 计算各个时间单位
        long second = totalSeconds % 60;
        long minute = (totalSeconds / 60) % 60;
        long hour = (totalSeconds / 3600) % 24;

        long totalDays = totalSeconds / (3600 * 24);

        long year = 1970; // Unix纪元开始年份
        long daysInYear;

        // 计算年份
        while (true) {
            daysInYear = isLeapYear(year) ? 366 : 365;
            if (totalDays >= daysInYear) {
                totalDays -= daysInYear;
                year++;
            } else {
                break;
            }
        }

        long[] daysInMonths = isLeapYear(year) ?
                new long[]{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} : // 闰年
                new long[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};  // 平年

        long month = 0;

        // 计算月份
        for (int i = 0; i < daysInMonths.length; i++) {
            if (totalDays >= daysInMonths[i]) {
                totalDays -= daysInMonths[i];
                month++;
            } else {
                break;
            }
        }

        // 剩余的天数即为日期
        long day = totalDays + 1;

        // 将各部分拼接成最终的字符串
        String formattedDate = String.format("%04d-%02d-%02d %02d:%02d:%02d",
                year, month + 1, day, hour, minute, second);

        System.out.println(formattedDate);
    }

    // 判断是否为闰年
    private static boolean isLeapYear(long year) {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }
}
